package cn.childspace.java_study.security.aes;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @desc AES加密工具
 * @author janker0718
 * @date 2016年7月14日
 */
public class AESUtil {
    /**
     * 加密
     * 
     * @param password
     * @param src
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(String password, String src) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(Constants.ENCRYPT_POLICY);
        kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, Constants.ENCRYPT_POLICY);
        Cipher cipher = Cipher.getInstance(Constants.ENCRYPT_POLICY);// 创建密码器
        byte[] byteContent = src.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
    }

    /**
     * 解密
     * @param password
     * @param content
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(String password, byte[] content) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密

    }

}
